package com.yupi.yupicturebackend.api.imagesearch.sub;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
/*获取以图搜图的页面地址*/
@Slf4j
public class GetImagePageUrlApi {

    /*获取图片页面地址*/
    public static String getImagePageUrl(String imageUrl){
        //准备请求参数
        Map<String,Object> formData=new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");

        //获取当前时间戳
        long timestamp = System.currentTimeMillis();
        //请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + timestamp;
        String acsToken = "1749529585922_1749535751928_8mMtAfgDeHW6iqdU6++nFntjj7NzUtLtVBOF0f8fMReZfq41AJjc72P9vlaxVoCa3nKI8qLP7eb/20ihxy2SE7dagvexztzS7y//vSQ95Cfn/wezVtZ77iqCg7IytWtCZPUzE9yrtimkVNguZ+6Y+U/teteapQyC95UqdH6D4tDQM85LRuQxL7o/SdBuh2aY12SAyPj2mbp+TdB+5gsAx1xETgfE/wKTc7ygr23jx70KteYR9gPiwf+x9vkQDnsijS9jPYT6fjMP67OAtUSsXpfvMtMONBoZG2FSnYKEc5p/WMNxes8RDGaN991DF8UbiN9N+tSSm4y2phZgv6dMquWbUvukFf/hzyIpr48iJaxETnQmcR6Z0FKa2Li/8rw4bU2T5hG7KzblEnFLZZqY8BG1txYShZTcQLf/J3u8CZdWcKSUa+cnb0f+5qSi9414";

        try{
            //发送POST请求到百度接口
            HttpResponse response = HttpRequest.post(url)
                    .form(formData)
                    .header("Acs-Token",acsToken)
                    .timeout(5000)
                    .execute();
            //判断响应状态
            if(HttpStatus.HTTP_OK!=response.getStatus()){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }

            //解析响应
            String responseBody = response.body();
            Map<String,Object> result = JSONUtil.toBean(responseBody, Map.class);

            //处理响应结果
            if(result==null||!Integer.valueOf(0).equals(result.get("status"))){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
            Map<String,Object> data = (Map<String, Object>)result.get("data");
            String rawUrl =(String)data.get("url");
            //对URL进行编码
            String searchResultUrl=URLUtil.decode(rawUrl);
            if(searchResultUrl==null){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "未返回有效结果");
            }
            return searchResultUrl;
        }catch (Exception e){
            log.error("搜索失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");
        }


    }

    public static void main(String[] args) {
        // 测试以图搜图功能
        String imageUrl = "https://www.codefather.cn/logo.png";
        String result = getImagePageUrl(imageUrl);
        System.out.println("搜索成功，结果 URL：" + result);
    }
}
